/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.command.user;

import com.sfkj.walk.aliyun.sms.SendSmsService;
import com.sfkj.walk.api.user.SendCaptchaCommand;
import io.generators.core.Generator;
import io.generators.core.RandomPositiveIntegerGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.commandhandling.CommandHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.sfkj.walk.Contants.CACHE_CAPTCHA_NAME;

@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Service
@Profile("!mock_captcha")
public class CaptchaCommandHandler {

    private final CacheManager cacheManager;
    private final SendSmsService sendSmsService;

    @CommandHandler
    public void handle(SendCaptchaCommand command) {
        String type = command.getType();
        String phone = command.getPhone();

        Generator<Integer> captchaGenerator = new RandomPositiveIntegerGenerator(1000, 9999);
        String captcha = captchaGenerator.next().toString();
        log.info("发送验证码:{},{}", phone, captcha);
        //  发送短信验证码
        if (Objects.equals(SendSmsService.REGISTER, command.getType())) {
            sendSmsService.sendRegisterCaptcha(phone, captcha);
        } else if (Objects.equals(SendSmsService.CHANGE_PASSWORD, type)) {
            sendSmsService.sendChangePasswordCaptcha(phone, captcha);
        }

        cacheManager.getCache(CACHE_CAPTCHA_NAME).put(phone, captcha);
    }

}